#!/usr/bin/env python
# encoding: utf-8

from app.views.api import route_api
from  flask import request,jsonify
import json

from app import db
from app.model import User
from app.model import Project
from app.model import Product
from app.model import Electronic
from app.model import ElectronicInCart

from app.common.libs.Logging import logger
from app.common.libs.Helper import getCurrentDate, getFormatDate
from app.common.libs.UserService import UserService

@route_api.route("/electronic/in/cart/add",methods = [ "GET","POST" ])
def ElectronicInCartAdd():
    resp = { 'code':20000,'message':'添加入库单成功~', 'data':{}}
    req = request.values

    sn = req['sn'] if 'sn' in req else ''
    if not sn:
        resp['code'] = -1
        resp['message'] = '需要sn'
        return jsonify( resp )

    electronic_info =  Electronic.query.filter_by( sn = sn  ).first()
    if not electronic_info:
        resp['code'] = -1
        resp['message'] = '元器件不存在,添加失败~'
        return jsonify( resp )

    user_info = UserService.getUserInfo(request)
    if not user_info:
        resp['code'] = -1
        resp['message'] = '用户不存在，添加失败~'
        return jsonify( resp )

    cart_info =  ElectronicInCart.query.filter( ElectronicInCart.electronic_id == Electronic.id  )\
                        .filter( Electronic.sn == sn  )\
                        .first()
    if cart_info:
        resp['code'] = -1
        resp['message'] = '当前元器件已添加至入库单中，无需重复添加~'
        return jsonify( resp )

    cart_model = ElectronicInCart()
    cart_model.user_id = user_info.id
    cart_model.electronic_id = electronic_info.id
    cart_model.count = 1
    cart_model.updated_time = cart_model.created_time = getCurrentDate()
    db.session.add(cart_model)
    db.session.commit()

    return jsonify( resp )

@route_api.route("/electronic/in/cart/find",methods = [ "GET","POST" ])
def ElectronicInCartFind():
    resp = { 'code':20000,'message':'查询成功~', 'data':{}}
    req = request.values

    user_info = UserService.getUserInfo(request)
    if not user_info:
        resp['code'] = -1
        resp['message'] = '用户不存在，查询失败~'
        return jsonify( resp )

    cart_info =  db.session.query(Electronic.id,
                                  Electronic.name,
                                  Electronic.stock,
                                  Project.name,
                                  Product.name,
                                  ElectronicInCart.id,
                                  ElectronicInCart.count,
                                  ElectronicInCart.created_time)\
                                .filter( ElectronicInCart.electronic_id == Electronic.id  )\
                                .filter( ElectronicInCart.user_id == User.id  )\
                                .filter( User.id == user_info.id  )\
                                .filter( Project.id == Electronic.project_id  )\
                                .filter( Project.id == Product.project_id  )\
                                .all()
    data = []
    for item in cart_info:
        data.append({
            'electronic_id': item[0],
            'name': item[1],
            'stock': item[2],
            'project': item[3],
            'product': item[4],
            'cart_id': item[5],
            'count': item[6],
            'created_time': getFormatDate(item[7]),
        })
    resp['data'] = data

    return jsonify( resp )

@route_api.route("/electronic/in/cart/delete",methods = [ "GET","POST" ])
def ElectronicInCartDelete():
    resp = { 'code':20000,'message':'删除成功~', 'data':{}}
    req = request.values
    electronics = req['electronics'] if 'electronics' in req else None
    items = []
    if electronics:
        items = json.loads(electronics)

    if not items or len( items ) < 1:
        resp['code'] = -1
        resp['message'] = '未选中元器件, 删除失败~'
        return jsonify(resp)

    user_info = UserService.getUserInfo(request)
    if not user_info:
        resp['code'] = -1
        resp['message'] = '用户不存在，无法删除~'
        return jsonify( resp )

    for item in items:
        ElectronicInCart.query.filter_by( electronic_id = item['electronic_id'],user_id = user_info.id ).delete()
    db.session.commit()

    return jsonify( resp )



